//
//  JYSportPlanViewController.m
//  FinderBox
//
//  Created by JiYi on 2018/10/12.
//  Copyright © 2018 JiYi. All rights reserved.
//

#import "JYSportPlanViewController.h"
#import "WSDatePickerView.h"


@interface JYSportPlanViewController ()
@property (weak, nonatomic) IBOutlet UITextField *totalStep;
@property (weak, nonatomic) IBOutlet UISwitch *pushSwitch;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;


@property (nonatomic,strong)StepModel * model;
@property (nonatomic, strong) UIButton * nextStep;

@end

@implementation JYSportPlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"设置运动计划";
    

    self.navigationController.navigationItem.title = @"";
    
    self.hbd_titleTextAttributes = @{NSForegroundColorAttributeName:UIColor.whiteColor};
    self.hbd_tintColor = UIColor.whiteColor;

    self.hbd_barTintColor = [UIColor jk_gradientFromColor:JYColorFromHex(0x41adf6) toColor:JYColorFromHex(0x1e53d8) withHeight:64 width:WIN_WIDTH];
    self.hbd_barShadowHidden = YES;
    
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedRowHeight = 0;


    UIView * footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIN_WIDTH, 180)];
    _nextStep = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextStep.backgroundColor = [UIColor jk_gradientFromColor:JYColorFromHex(0x41adf6) toColor:JYColorFromHex(0x1e53d8) withHeight:40 width:WIN_WIDTH];
    _nextStep.frame = CGRectMake(15, 20, WIN_WIDTH - 30, 40);
    //  阴影
    _nextStep.layer.shadowOffset =  CGSizeMake(1, 1);
    _nextStep.layer.shadowOpacity = 0.5;
    _nextStep.layer.shadowColor =  JYColorFromHex(0x41adf6).CGColor;
    
    [_nextStep setTitle:@"保存" forState:UIControlStateNormal];
    [_nextStep setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _nextStep.titleLabel.textAlignment = NSTextAlignmentCenter;
    _nextStep.layer.cornerRadius = 2;
    [_nextStep addTarget:self action:@selector(savaClick) forControlEvents:UIControlEventTouchUpInside];
    
    [footerView addSubview:_nextStep];
    
    self.tableView.tableFooterView = footerView;
    
    //  设置初始化数据
    
    if (self.onceTag) {
        [self.nextStep setTitle:@"开始" forState:UIControlStateNormal];
    }else{
        [self.nextStep setTitle:@"保存" forState:UIControlStateNormal];
        if (self.everyModel) {
            self.totalStep.text = [NSString stringWithFormat:@"%ld",self.everyModel.totalStep];
            self.pushSwitch.on = self.everyModel.isNot;
            self.timeLabel.text = [self.everyModel.notDate jk_stringWithFormat:@"hh:mm"];
        }
    }
    
    UIButton * yinsi = [UIButton buttonWithType:UIButtonTypeCustom];
    [yinsi setTitle:@"点击查看《隐私协议》" forState:UIControlStateNormal];
    [yinsi setTitleColor:JYMainColor forState:UIControlStateNormal];
    yinsi.titleLabel.font = [UIFont systemFontOfSize:12.0f];
    [footerView addSubview:yinsi];
    
    [yinsi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.nextStep.mas_bottom).offset(10);
    }];
    [yinsi addTarget:self action:@selector(yinsiClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)yinsiClick {
    JYSubWebViewController * webVC = [[JYSubWebViewController alloc] init];
    webVC.hidesBottomBarWhenPushed = YES;
    
    AVObject * obj = [AVObject objectWithClassName:@"HtmlManager" objectId:@"5bc59c570b6160006ff4b3ca"];
    [obj fetchInBackgroundWithBlock:^(AVObject * _Nullable object, NSError * _Nullable error) {
        webVC.urlStr = object[@"url"];
        webVC.title = @"隐私协议";
        [self.navigationController pushViewController:webVC animated:YES];
    }];
}



- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (StepModel *)model {
    if (!_model) {
        _model = [StepModel new];
    }
    return _model;
}

- (void)setOnceTag:(BOOL)onceTag {
    _onceTag = onceTag;
    
}
- (void)setEveryModel:(StepModel *)everyModel {
    _everyModel = everyModel;
    
}




#pragma mark - 保存安康牛
- (void)savaClick {
    if (!self.everyModel && !self.model.notDate && self.pushSwitch.on) {
        [MBProgressHUD showInfoMessage:@"请选择通知时间"];
        return;
    }
    
    
    self.model.isNot = self.pushSwitch.on;
    self.model.updateTime =
    self.model.createTime =[[NSDate date] timeIntervalSince1970];
    self.model.totalStep = [self.totalStep.text integerValue];
    NSString * identifer = [NSString stringWithFormat:@"%llu",self.model.createTime];
    self.model.identifer = NotificationIdentifer(identifer);
    __weak typeof(self) weakSelf = self;
    
    if (!self.onceTag) {
        if (self.everyModel) {
            self.model.createTime = self.everyModel.createTime;
            self.model.updateTime = [[NSDate date] timeIntervalSince1970];
            self.model.identifer = self.everyModel.identifer;
            self.model.notDate = self.everyModel.notDate;
        }
        self.model.isEveryDay = YES;
        [UserNotificationManager removeNotificationWithIdentifer:self.model.identifer];
        UNMutableNotificationContent * content = [UserNotificationManager contentWithTitle:nil
                                                                                  subTitle:[NSString stringWithFormat:@"今日目标%ld步，看看您完成了多少",self.model.totalStep]
                                                                                      body:nil
                                                                                     sound:nil];
        [UserNotificationManager addNotificationWithContent:content
                                                  identifer:self.model.identifer
                                                   isRepeat:YES
                                             dateComponents:[UserNotificationManager componentsWithEveryDayWithDate:self.model.notDate]
                                          completionHandler:^(NSError *error) {
                                              [GCDQueue executeInMainQueue:^{
                                                  BOOL success = NO;
                                                  if (!error && weakSelf.everyModel) {
                                                      NSString * sql = [NSString stringWithFormat:@"createTime = %llu",weakSelf.model.createTime];
                                                      [WHCSqlite update:weakSelf.model where:sql];
                                                      success = YES;
                                                  }else if (!error){
                                                      [WHCSqlite insert:weakSelf.model];
                                                      success = YES;
                                                  }
                                                  if (success) {
                                                      [MBProgressHUD showSuccessMessage:@"设置成功"];
                                                      if (weakSelf.settingBlock) {
                                                          weakSelf.settingBlock(success, weakSelf.model);
                                                      }
                                                      [self.navigationController popViewControllerAnimated:YES];
                                                      [[NSNotificationCenter defaultCenter] postNotificationName:@"finishSettingModel" object:weakSelf.model];
                                                  }else{
                                                      [MBProgressHUD showSuccessMessage:@"设置失败"];
                                                  }
                                              }];
                                              
                                          }];
    }else{
        self.model.isEveryDay = NO;
        UNMutableNotificationContent * content = [UserNotificationManager contentWithTitle:nil
                                                                                  subTitle:[NSString stringWithFormat:@"运动目标%ld步，看看您完成了多少",self.model.totalStep]
                                                                                      body:nil
                                                                                     sound:nil];
        [UserNotificationManager addNotificationWithContent:content
                                                  identifer:self.model.identifer
                                                   isRepeat:NO
                                             dateComponents:[UserNotificationManager componentsWithDate:self.model.notDate]
                                          completionHandler:^(NSError *error) {
                                              [GCDQueue executeInMainQueue:^{
                                                  if (!error){
                                                      [WHCSqlite insert:weakSelf.model];
                                                      if (self.settingBlock) {
                                                          self.settingBlock(YES, weakSelf.model);
                                                      }
                                                      [self.navigationController popViewControllerAnimated:YES];
                                                      [[NSNotificationCenter defaultCenter] postNotificationName:@"finishSettingModel" object:weakSelf.model];
                                                      [MBProgressHUD showSuccessMessage:@"设置成功"];
                                                  }else{
                                                      [MBProgressHUD showSuccessMessage:@"设置失败"];
                                                  }
                                              }];
                                              
                                          }];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        [self chooseTGime];
    }
}
- (void)chooseTGime {
    __weak typeof(self) weakSelf = self;
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowHourMinute scrollToDate:[NSDate date] CompleteBlock:^(NSDate *selectDate) {
        NSDate * todayDate = [NSDate date];
        NSString * timeString = [NSString stringWithFormat:@"%@ %@",[todayDate jk_stringWithFormat:@"yyyy-MM-dd"],[selectDate jk_stringWithFormat:@"hh:mm"]];
        weakSelf.timeLabel.text = [selectDate jk_stringWithFormat:@"hh:mm"];
        weakSelf.model.notDate = [NSDate jk_dateWithString:timeString format:@"yyyy-MM-dd hh:mm"];
        
    }];
    datepicker.yearLabelColor = [UIColor clearColor];
    datepicker.dateLabelColor = [UIColor blackColor];//年-月-日-时-分 颜色
    datepicker.datePickerColor = [UIColor blackColor];//滚轮日期颜色
    datepicker.doneButtonColor = [UIColor jk_gradientFromColor:JYColorFromHex(0x41adf6) toColor:JYColorFromHex(0x1e53d8) withHeight:64 width:WIN_WIDTH];//确定按钮的颜色
    [datepicker show];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
